using System;
using System.Collections.Generic;
using System.Text;

namespace BlackjackGUI
{
   class CDeck
   {
      public CDeck()
      {
         m_played = new LinkedList<CCard>();
         m_unplayed = new LinkedList<CCard>();

         for (int ii = 0; ii < 13; ii++)
         {
            for(int jj = 0; jj < 4; jj++)
            {
               CCard card = new CCard((ValueEnum)(ii+1), (SuitEnum)jj);
               m_unplayed.AddLast(card);
            }
         }
      }

      ~CDeck()
      {
         ClearDeck();
      }

      public void Shuffle()
      {
         // Move all cards to played pile
         while (m_unplayed.Count > 0)
         {
            CCard temp = m_unplayed.First.Value;
            m_played.AddLast(temp);
            m_unplayed.RemoveFirst();
         }

         // Randomly move cards back to unplayed pile
         Random rand = new Random();
         while (m_played.Count > 0)
         {
            int index = rand.Next(m_played.Count);
            LinkedListNode<CCard> iter = m_played.First;
            for (int ii = 0; ii < index; ii++)
            {
               iter = iter.Next;
            }
            m_unplayed.AddLast(iter.Value);
            m_played.Remove(iter);
         }
      }

      private void ClearDeck()
      {
         if (m_played != null)
         {
            m_played.Clear();
            m_played = null;
         }
         if (m_unplayed != null)
         {
            m_unplayed.Clear();
            m_unplayed = null;
         }
      }

      public CCard DealOneCard()
      {
         CCard retVal;
         retVal = m_unplayed.First.Value;
         m_unplayed.RemoveFirst();
         m_played.AddLast(retVal);
         return retVal;
      }

      public LinkedList<CCard> GetAllCards()
      {
         Shuffle();
         return m_unplayed;
      }

      private LinkedList<CCard> m_unplayed;
      private LinkedList<CCard> m_played;
      
   }
}
